package com.youdoneed.common.service;

import com.querydsl.sql.SQLQueryFactory;
import com.youdoneed.base.application.AppException;
import com.youdoneed.base.application.ResultMessage;
import com.youdoneed.common.model.FileInfo;
import com.youdoneed.common.model.VersionInfo;
import com.youdoneed.common.query.QVersionInfo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

@Service
public class VersionServiceImpl implements VersionService{
    private static final Logger LOGGER = LoggerFactory.getLogger(FileService.class);


    @Autowired
    private FileService fileService;
    @Autowired
    private SQLQueryFactory queryFactory;
    private QVersionInfo qVersionInfo = QVersionInfo.VersionInfo;






    /**
     * 获取最新的版本信息
     * @return
     */
    @Override
    @Transactional
    public VersionInfo getNewestVersionInfo(){
        final int NOT_DELETE = 0;
        List<VersionInfo> versionInfos=queryFactory.selectFrom(qVersionInfo)
                .where(qVersionInfo.deleted.gt(NOT_DELETE))
                .orderBy(qVersionInfo.createTime.desc())
                .fetch();

        VersionInfo versionInfo =null;
        if (versionInfos!=null && versionInfos.size()>0){
            versionInfo=versionInfos.get(0);
        }

        return versionInfo;

    }


    /**
     * 上传最新包
     * @param versionCode
     * @param versionName
     * @param description
     * @param apkFile
     * @return
     */
    @Transactional
    @Override
    public long upLoadNewApk(int versionCode, String versionName, String description, MultipartFile apkFile) {
        VersionInfo versionInfo = new VersionInfo();
        versionInfo.setVersionCode(versionCode);
        versionInfo.setVersionName(versionName);
        versionInfo.setCreateTime(new Date());
        versionInfo.setDescription(description);

        //非0代表此条记录为未删除，用户可见
        versionInfo.setDeleted(1);

        FileInfo fileInfo =fileService.saveFile(apkFile);
        if (fileInfo==null){
            return 0;
        }else {
            versionInfo.setApkUrl(fileInfo.getUrl());
            return queryFactory.insert(qVersionInfo)
                    .populate(versionInfo)
                    .execute();
        }

    }





}
